import { onBeforeMount, PropType, ref, watch } from "vue";
import { i18n } from "@/i18n";
import { get } from "lodash-es";
import { ElMessageBox } from "element-plus";
import { addExtSetting, deleteExtSetting, listExtSettingRequest } from "@/api/project/extSetting";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";

export interface Field {
  value: string;
  label: string;
  scheme?: any;
  type?: string;
}

export interface Condition {
  formItemId: string;
  method: string;
  value: string;
  field?: Field;
  defaultValueType?: string;
}

export interface FilterParams {
  rel: string;
  conditionList: Condition[];
}

export const dataFilterProps = {
  fields: {
    type: Array as PropType<Field[]>,
    default: () => []
  },
  formDataFilter: {
    type: Object as PropType<FilterParams>,
    default: () => {}
  },
  formKey: {
    type: String,
    required: false
  },
  //是否 显示快捷条件
  showQuickFilter: {
    type: Boolean,
    default: false
  }
};

export const dataFilterEmits = ["filter"];

export function useDataFilter(props: any, emit: any) {
  const relList = ref([
    {
      label: i18n.global.t("form.dataFilter.allData"),
      value: "AND"
    },
    {
      label: i18n.global.t("form.dataFilter.arbitrary"),
      value: "OR"
    }
  ]);

  const typeIncludeMethods = ref<any>({
    INPUT: ["EQ", "NE", "GT", "LT", "GE", "LE", "INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    TEXTAREA: ["EQ", "NE", "GT", "LT", "GE", "LE", "INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    NUMBER: ["EQ", "NE", "GT", "LT", "GE", "LE", "IS_NULL", "NOT_NULL"],
    SELECT: ["EQ", "NE", "INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    RADIO: ["EQ", "NE", "INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    CHECKBOX: ["EQ", "NE", "INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    DATE: ["EQ", "NE", "GT", "LT", "GE", "LE", "IS_NULL", "NOT_NULL", "TIME_RANGE"],
    PROVINCE_CITY: ["INCLUDE", "NOT_INCLUDE", "IS_NULL", "NOT_NULL"],
    USER: ["INCLUDE", "IS_NULL", "NOT_NULL"],
    workflowStatus: ["INCLUDE", "IS_NULL", "NOT_NULL"]
  });

  const conditionRuleOptions = ref([
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.EQ"), value: "EQ" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.NE"), value: "NE" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.GT"), value: "GT" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.LT"), value: "LT" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.GE"), value: "GE" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.LE"), value: "LE" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.INCLUDE"), value: "INCLUDE" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.NOT_INCLUDE"), value: "NOT_INCLUDE" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.IS_NULL"), value: "IS_NULL" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.NOT_NULL"), value: "NOT_NULL" },
    { label: i18n.global.t("form.dataFilter.conditionRuleOptions.TIME_RANGE"), value: "TIME_RANGE" }
  ]);

  const timeRanges = ref([
    { label: i18n.global.t("form.dataFilter.today"), value: "TODAY" },
    { label: i18n.global.t("form.dataFilter.yesterday"), value: "YESTERDAY" },
    { label: i18n.global.t("form.dataFilter.thisWeek"), value: "WEEK" },
    { label: i18n.global.t("form.dataFilter.lastWeek"), value: "LAST_WEEK" },
    { label: i18n.global.t("form.dataFilter.thisMonth"), value: "MONTH" },
    { label: i18n.global.t("form.dataFilter.lastMonth"), value: "LAST_MONTH" },
    { label: i18n.global.t("form.dataFilter.thisQuarter"), value: "QUARTER" },
    { label: i18n.global.t("form.dataFilter.lastQuarter"), value: "LAST_QUARTER" },
    { label: i18n.global.t("form.dataFilter.thisYear"), value: "YEAR" },
    { label: i18n.global.t("form.dataFilter.lastYear"), value: "LAST_YEAR" }
  ]);

  const filterParams = ref<FilterParams>({
    rel: "AND",
    conditionList: []
  });

  const flowStatusList = ref([
    { label: "审批中", value: "审批中" },
    { label: "已通过", value: "已通过" },
    { label: "已拒绝", value: "已拒绝" },
    { label: "已取消", value: "已取消" }
  ]);

  const defaultDateTimeFormat = ref("YYYY-MM-DD HH:mm:ss");

  //避免 watch死循环
  let skipNextEmit = false;

  watch(
    () => filterParams.value,
    val => {
      console.log(filterParams);
      if (skipNextEmit) {
        skipNextEmit = false;
        return;
      }
      // 过滤掉没有用的数据
      emit("filter", val);
    },
    { deep: true }
  );

  watch(
    () => props.formDataFilter,
    newVal => {
      console.log(newVal);
      skipNextEmit = true;
      filterParams.value = {
        ...filterParams.value,
        ...newVal,
        conditionList: newVal?.conditionList
          ? newVal.conditionList.map((item: Condition) => ({
              ...item,
              field: props.fields?.find((field: Field) => field.value === item.formItemId)
            }))
          : []
      };
    },
    { deep: true, immediate: true }
  );

  onBeforeMount(() => {
    if (props.showQuickFilter) {
      queryFilterList();
    }
  });

  const getFiledType = (id: string): string => {
    if (id === "createBy" || id === "updateBy") {
      return "USER";
    } else if (["createTime", "updateTime", "beginTime"].includes(id)) {
      return "DATE";
    }
    return id.replace("label", "").replace(/\d+./g, "").replace("-", "").toUpperCase();
  };

  const getFieldScheme = (id: string) => {
    return props.fields?.find((item: Field) => item.value === id)?.scheme;
  };

  const getObjValue = (obj: any, key: string, defaultValue: any) => {
    return get(obj, key, defaultValue);
  };

  const handleConditionChange = (value: string, item: Condition) => {
    const field = props.fields?.find((field: Field) => field.value === value);
    item["field"] = field;
    if (field?.scheme?.config?.defaultValue) {
      item["defaultValueType"] = Array.isArray(field.scheme.config.defaultValue) ? "ARRAY" : "STRING";
    } else {
      item["defaultValueType"] = field?.type === "USER" ? "ARRAY" : "STRING";
    }
  };

  const getConditionRuleList = (item: Condition) => {
    if (!item?.formItemId) return [];
    const field = props.fields?.find((field: Field) => field.value === item.formItemId);
    const type = field?.type;
    let typeIncludeMethod = type ? typeIncludeMethods.value[type] : undefined;
    if (!type || !typeIncludeMethod) {
      typeIncludeMethod = ["IS_NULL", "NOT_NULL"];
    }
    return conditionRuleOptions.value.filter(rule => typeIncludeMethod?.includes(rule.value));
  };

  const removeConditionHandle = (index: number) => {
    filterParams.value.conditionList.splice(index, 1);
  };

  const addConditionHandle = () => {
    filterParams.value.conditionList.push({
      formItemId: "",
      method: "",
      value: ""
    });
  };

  const handleCleanFilter = () => {
    filterParams.value.conditionList = [];
  };

  const handleSaveFilter = () => {
    ElMessageBox.prompt(i18n.global.t("form.dataFilter.enterFilterName"), i18n.global.t("common.save"), {
      confirmButtonText: i18n.global.t("common.enter"),
      cancelButtonText: i18n.global.t("common.cancel")
    })
      .then(({ value }) => {
        addExtSetting({
          formKey: props.formKey,
          settings: JSON.stringify({
            filterName: value,
            filterParams: filterParams.value
          }),
          type: "formDataFilter"
        }).then(() => {
          MessageUtil.success(i18n.global.t("common.saveSuccess"));
          queryFilterList();
        });
      })
      .catch(() => {});
  };

  const filterList = ref<any[]>([]);

  const queryFilterList = () => {
    listExtSettingRequest({
      formKey: props.formKey,
      type: "formDataFilter"
    }).then(res => {
      filterList.value = res!.data;
    });
  };

  const handleDeleteFilter = (id: number) => {
    MessageBoxUtil.confirm(i18n.global.t("common.deleteConfirm"), () => {
      deleteExtSetting(id).then(() => {
        queryFilterList();
      });
    });
  };

  const handleUsedFilter = (item: any) => {
    filterParams.value = item.filterParams;
  };

  const getFilterData = () => {
    return {
      ...filterParams.value,
      conditionList: filterParams.value.conditionList
        .filter((item: Condition) => {
          return item.formItemId && item.method;
        })
        .map(item => {
          // 前端用来过滤需要  但是不要给后端 存储起来很大
          delete item.field;
          return item;
        })
    };
  };

  return {
    relList,
    typeIncludeMethods,
    conditionRuleOptions,
    timeRanges,
    filterParams,
    flowStatusList,
    defaultDateTimeFormat,
    getFiledType,
    getFieldScheme,
    getObjValue,
    handleConditionChange,
    getConditionRuleList,
    removeConditionHandle,
    addConditionHandle,
    handleCleanFilter,
    handleSaveFilter,
    filterList,
    queryFilterList,
    handleDeleteFilter,
    handleUsedFilter,
    getFilterData
  };
}
